package com.mikel.monitor.misc;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import com.mikel.monitor.domain.ZbNetworkState;

public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }
    
    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
            
            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                
                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                
                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }
    
    /** */
    public static class SerialReader implements Runnable 
    {
        InputStream in;
        
        boolean persist =true;
        
        boolean interruptor = false;
        double temperatura = 0;
        String luminosidad;
        int consumo = 0;
        
        public SerialReader ( InputStream in )
        {
            this.in = in;
        }
        
        public void run ()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            
            String packet = null;
            String previousPacket = null;
            try
            {
                while ( ( len = this.in.read(buffer)) > -1 )
                {
//                    System.out.print(str1=new String(buffer,0,len));
                    packet=new String(buffer,0,len);
                    if(!packet.equals(previousPacket)) {
                    	String hexPacket = toHex(packet);
                    	System.out.println("Mik: "+hexPacket);
                    	packetDecode(hexPacket);
//                    	printState();
                    }
                    previousPacket = packet;
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
        
        public String toHex(String arg) {
            return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
        }
        
        
		public void packetDecode(String hexFrame) {
			
			//Write address in little endian!!! e.g: address 0x1234 id 3412
			String srcAddrLight = "2507";
			// case switch event
			if (hexFrame.contains("000003010002")) {
				interruptor = !interruptor;
				
				Date date = new Date();
				
				ZbNetworkState zbNetworkState = new ZbNetworkState();
				zbNetworkState.setNombreParametro("Interruptor magnético");
				zbNetworkState.setValor("evento");
				zbNetworkState.setFecha(date);
				zbNetworkState.setNodo("3");
				
				if(persist)
				zbNetworkState.persist();
				
				
				printState();
			} 
			
			// case light sensor
			else if (hexFrame.contains("a000029") && hexFrame.contains(srcAddrLight)) {
				
				int i = hexFrame.indexOf("a000029");
				i += 7;
				
				
				String lightString = hexFrame.substring(i, i + 4);
				String lightStringL = hexFrame.substring(i, i + 2);
				String lightStringH = hexFrame.substring(i + 2, i + 4);

				int lightInt = Integer.parseInt(lightStringH + lightStringL, 16);

				if (lightInt > 4000) luminosidad= "Alta";
				else if (lightInt > 1200) luminosidad= "Media";
				else luminosidad= "Baja";
				
				Date date = new Date();
				
				ZbNetworkState zbNetworkState = new ZbNetworkState();
				zbNetworkState.setNombreParametro("Luminosidad");
				zbNetworkState.setValor(luminosidad);
				zbNetworkState.setFecha(date);
				zbNetworkState.setNodo("2");
				
				if(persist)
					zbNetworkState.persist();
				
				// temperatura = (tempIntH*100+tempIntL)/100;
				printState();
			}
			
			// case temperature sensor
			else if (hexFrame.contains("a000029")) {

				int i = hexFrame.indexOf("a000029");
				i += 7;

				String tempString = hexFrame.substring(i, i + 4);
				String tempStringL = hexFrame.substring(i, i + 2);
				String tempStringH = hexFrame.substring(i + 2, i + 4);
				int tempIntL = Integer.parseInt(tempStringL, 16);
				int tempIntH = Integer.parseInt(tempStringH, 16);
				int tempInt = Integer.parseInt(tempStringH + tempStringL, 16);
				double temp = (double) tempInt / 100;

				// Round to one decimal
				temperatura = (double) Math.round(temp * 10) / 10;
				
				Date date = new Date();
				
				ZbNetworkState zbNetworkState = new ZbNetworkState();
				zbNetworkState.setNombreParametro("Temperatura");
				zbNetworkState.setValor(String.valueOf(temperatura)+" ºC");
				zbNetworkState.setFecha(date);
				zbNetworkState.setNodo("4");
				
				if(persist)
				zbNetworkState.persist();
				
				// temperatura = (tempIntH*100+tempIntL)/100;
				printState();
			}

			
			// case plug - electric consumption
			else if (hexFrame.contains("0a00042a")) {
				
				int i = hexFrame.indexOf("0a00042a");
				i += 8;
				
				String tempString = hexFrame.substring(i, i + 6);
				
				String consumString0 = hexFrame.substring(i, i + 2);
				String consumString1 = hexFrame.substring(i + 2, i + 4);
				String consumString2 = hexFrame.substring(i + 4, i + 6);
				
				consumo = Integer.parseInt(consumString2 + consumString1 + consumString0, 16);
			
				
				Date date = new Date();
				ZbNetworkState zbNetworkState = new ZbNetworkState();
				zbNetworkState.setNombreParametro("Consumo eléctrico");
				zbNetworkState.setValor(String.valueOf(consumo)+" W");
				zbNetworkState.setFecha(date);
				zbNetworkState.setNodo("1");
				
				if(persist)
				zbNetworkState.persist();
				
				
				printState();
			}

		}

		public void printState() {
			System.out.println("Interruptor activado: " + interruptor);
			System.out.println("Temperatura: " + temperatura);
			System.out.println("Luminosidad: " + luminosidad);
			System.out.println("Consumo eléctrico: " + consumo + " W");
			System.out.println("-----------------------------");
		}
	}


    /** */
    public static class SerialWriter implements Runnable 
    {
        OutputStream out;
        
        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }
        
        public void run ()
        {
            try
            {                
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }                
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }
    

    
    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM13");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}